package com.zzc.qqchat.controller;

import com.zzc.qqchat.repository.LoginRespository;
import com.zzc.qqchat.domain.UserInfor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class LoginController {

    @Resource
    LoginRespository loginRespository;


    @GetMapping("/log")
    public String log(){
        return "/message/login";
    }

    @ResponseBody
    @PostMapping("/login")
    public String login(int userId, String password, HttpServletRequest request){

        String result="false";
        ArrayList<UserInfor> userInfors = loginRespository.findByUserId(userId);
        if(userInfors.get(0).getPassword().equals(password)){
            request.getSession().setAttribute("loginUserId",userId);
            result = "true";
        }
        return result;
    }

    @ResponseBody
    @PostMapping("/myinfor")
    public ArrayList<UserInfor> myinfor(int userId){

        ArrayList<UserInfor> userInfors = loginRespository.findByUserId(userId);
        return userInfors;
    }

    @ResponseBody
    @PostMapping("/userinfor")
    public String userinfor(int userId){

        ArrayList<UserInfor> userInfors = loginRespository.findByUserId(userId);
        return userInfors.get(0).getPicture();

    }

    @ResponseBody
    @PostMapping("/registered")
    public int registered(String password,String userName,String picture){

        List<UserInfor> userInfors = loginRespository.findAll();
        int id = userInfors.size()+1;
        UserInfor userInfor = new UserInfor();
        userInfor.setUserId(id);
        userInfor.setPicture(picture);
        userInfor.setPassword(password);
        userInfor.setUserName(userName);
        loginRespository.save(userInfor);
        return id;

    }
}
